<?php
namespace Qwadmin\Controller;

class ReferlinkController extends ComController{
    /**
     * 创建推广链接
     */
    public function create(){
        $description = htmlspecialchars(I("description") , ENT_NOQUOTES);
        $bookid = I("bookid" , 0 , 'intval');
        $chapterid = I("chapterid" , 0 , 'intval');
        
        if($description == ""){
            $this->ajaxReturn(['status' => 0 , 'msg' => '派单渠道名称']);
        }
        
        if($bookid == 0 || $chapterid == 0){
            $this->ajaxReturn(['status' => 0 , 'msg' => '非法操作']);
        }
        
        $data = [
            'uid'           => session("uid"),
            'description'   => $description,
            'type'          => 1,
            'bookid'        => $bookid,
            'chapterid'     => $chapterid,
            'created'       => time()
        ];
        $rows =  M("referral_links")->add($data);
        
        $rows ? $this->ajaxReturn(['status' => 1 , 'msg' => '添加成功']) : $this->ajaxReturn(['status' => 0 , 'msg' => '添加失败']);
    }
    
    /**
     *  推广链接
     */
    public function index(){
        //防止sql 注入，where 条件一定用tp方法构建
        $prefix = C("DB_PREFIX");
        $keyword = htmlspecialchars(I("q" , ''));
        if($keyword != ''){
            $where["{$prefix}referral_links.description"] = ['LIKE' , "%" . $keyword . "%"];
            $where['book_title'] = ['LIKE' , "%" .$keyword . "%"];
            $where['_logic'] = 'or';
            $map['_complex'] = $where;
        }
        
        if(session("uid") != 1){
            $map['uid'] = session("uid");
        }
        
        $p = I("p" , 1 , 'intval');
        
        $data = D("referlink")->getList($map, $p);       
        $domain = D("domain")->getDomain(2);
        $this->assign("page" , $data['page']);
        $this->assign("list" , $data['list']);
        $this->assign("domain" , $domain);
        $this->display();
    }
    
    /**
     *  推广展示内容
     */
    public function content(){
        $id = I("id" , 0 , 'intval');
        $chapter = M("referral_links")->where(['id' => $id])->find();
        $domain = D("domain")->getDomain(1);
        $api_url = "http://{$domain}/api/book/get_content/id/{$chapter['chapterid']}";
        $json = https_request($api_url);
        $json_arr = json_decode($json , true);
        $this->assign("domain" , $domain);
        $this->assign("data" , $json_arr);
        $this->assign("chapter" , $chapter);
        $this->display();
    }
    
    /**
     *  增加阅读数
     */
    public function incrview(){
        $id = I("id" , 0 , 'intval');
        M("referral_links")->where(['id' => $id])->setInc("hits" , 1);
    }
    
}
